package com.sophie.dao.impl;

import com.sophie.DTO.CommentDTO;
import com.sophie.dao.BaseDAO;
import com.sophie.dao.ICommentDAO;
import com.sophie.entity.Comment;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Rowena
 * @CreateTime: 2024-09-11 17:13:03
 * @Version: 1.0
 */

public class CommentDAOImpl extends BaseDAO implements ICommentDAO {
    @Override
    public int addComment(Comment comment) {
        try {
            String sql="insert into comment(zoneid,commenttime,userid,contenttext) values(?,?,?,?)";
            int update = super.update(sql, comment.getZoneid(), comment.getCommenttime(), comment.getUserid(), comment.getContenttext());
            if(update>0){
                return update;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<CommentDTO> getCommentByZoneId(Integer id) {
        try {
            String sql="select zoneid,commenttime,userid,contenttext,u.`name` as username,avatar " +
                    "from `comment` c,`user` u " +
                    "where c.userid=u.id and zoneid=? ORDER BY commenttime DESC;";
            List<CommentDTO> commentList = super.getAll(sql, CommentDTO.class, id);
            if(commentList.size()>0){
                return commentList;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long countCommentByZoneId(Integer id) {
        try {
            String sql="select count(*) from `comment` where zoneid=?";
            Long scalar = super.getScalar(sql, id);
            if(scalar>0){
                int update = super.update("update zone set commentcount=? where id=?",scalar ,id);
                if(update>0){
                    return scalar;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
